<?php
namespace App\Http\Controllers\Admin;

use App\Models\Goods;
use App\Http\Resources\Admin\GoodsCollection;
use Illuminate\Http\Request;

class GoodsController extends Controller
{
    protected $_rules = [
        [
            'image' => 'required|string',
            'name' => 'required|string|max:50',
            'description' => 'string',
            'item_id' => 'string',
            'cost_money'=>'integer',
            'cost_coin'=>'integer',
            'cost_diamond'=>'integer',
            'category_id'=>'required|integer',
            'status'=>'required|integer',
        ],
    ];

    public function index()
    {
    	$orderBy = $this->getOrderByQuery([
    		'id',
            'status',
            'category_id',
            'cost_money',
            'cost_coin',
            'cost_diamond',
    	]);

        $filters=$this->getFilterConditions(['category_id']);

    	$result = Goods::where($filters)
        ->orderByRaw($orderBy)
    	->orderByDesc('id')
    	->paginate(per_page());
        return new GoodsCollection($result);
    }

    public function store(Request $request)
    {
        $inputs = $this->validate($request, $this->_rules[0]);

        $record = Goods::create($inputs);

        return $record;
    }

    public function update(Request $request, $id)
    {
        $record = Goods::findOrFail($id);

        $inputs = $this->validate($request, $this->allowNullRules($this->_rules[0]));
        $inputs = $this->unsetEmptyFields($inputs, ['image']);

        $record->update($inputs);
        return $record;
    }

    public function destroy($id)
    {
        $record = Goods::findOrFail($id);
        $result = Goods::destroy($id);
        return [];
    }
}
